package com.example.healthmanagement.ui.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.healthmanagement.R;
import com.example.healthmanagement.adapter.AddFoodEnergyAdapter;
import com.example.healthmanagement.bean.FoodEnergy;
import com.example.healthmanagement.databinding.DialogEditEnergyBinding;
import com.example.healthmanagement.util.MySqliteOpenHelper;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * 食物热量
 */
public class AddFoodEnergyActivity extends AppCompatActivity {
    MySqliteOpenHelper helper = null;
    private Activity myActivity;//上下文
    private TabLayout tabTitle;
    private RecyclerView rvList;
    private EditText etSearch;
    private AddFoodEnergyAdapter foodEnergyAdapter;
    private LinearLayout llEmpty;
    private String[] state = {"0", "1", "2", "3", "4", "5"};
    private String[] title = {"五谷类", "肉类", "水果类", "蔬菜类", "海鲜类", "奶类"};
    private String typeId = "0";
    private List<FoodEnergy> foodEnergyList;
    private boolean isManager = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_food_energy);
        isManager = getIntent().getBooleanExtra("isManager", false);
        if (isManager) {
            View viewById = findViewById(R.id.iv_add);
            viewById.setVisibility(View.VISIBLE);
            viewById.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showAddDialog();
                }
            });
        }
        myActivity = this;
        helper = new MySqliteOpenHelper(this);
        tabTitle = findViewById(R.id.tab_title);
        etSearch = findViewById(R.id.et_search);
        rvList = findViewById(R.id.rv_list);
        llEmpty = findViewById(R.id.ll_empty);
        etSearch.setVisibility(View.VISIBLE);
        //获取控件
        initView();
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                loadData();
            }
        });
    }

    private void showAddDialog() {
        DialogEditEnergyBinding binding = DialogEditEnergyBinding.inflate(getLayoutInflater());
        AlertDialog show = new AlertDialog.Builder(this).setView(binding.getRoot()).show();
        binding.btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                show.dismiss();
            }
        });
        binding.btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String carbon = binding.etCarbon.getText().toString();
                String fat = binding.etFat.getText().toString();
                String heat = binding.etHeat.getText().toString();
                String name = binding.etName.getText().toString();
                String protein = binding.etProtein.getText().toString();
                String quantity = binding.etQuantity.getText().toString();
                if (carbon.isEmpty() || fat.isEmpty() || heat.isEmpty() || name.isEmpty() || protein.isEmpty() || quantity.isEmpty()) {
                    return;
                }
                FoodEnergy foodEnergy = new FoodEnergy();
                foodEnergy.setTypeId(Integer.parseInt(typeId));
                foodEnergy.setFood(name);
                foodEnergy.setCarbon(Double.parseDouble(carbon));
                foodEnergy.setFat(Double.parseDouble(fat));
                foodEnergy.setHeat(heat);
                foodEnergy.setProtein(Double.parseDouble(protein));
                foodEnergy.setQuantity(quantity);
                SQLiteDatabase writableDatabase = helper.getWritableDatabase();
                writableDatabase.insert("food_energy", null, foodEnergy.toContentValues());
                show.dismiss();
                loadData();
            }
        });
    }

    /**
     * 初始化页面
     */
    private void initView() {
        tabTitle.setTabMode(TabLayout.MODE_SCROLLABLE);
        //设置tablayout距离上下左右的距离
        //tab_title.setPadding(20,20,20,20);

        //为TabLayout添加tab名称
        for (int i = 0; i < title.length; i++) {
            tabTitle.addTab(tabTitle.newTab().setText(title[i]));
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(myActivity);
        //=1.2、设置为垂直排列，用setOrientation方法设置(默认为垂直布局)
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //=1.3、设置recyclerView的布局管理器
        rvList.setLayoutManager(layoutManager);
        //==2、实例化适配器
        //=2.1、初始化适配器
        foodEnergyAdapter = new AddFoodEnergyAdapter(0, isManager);
        //=2.3、设置recyclerView的适配器
        rvList.setAdapter(foodEnergyAdapter);
        loadData();
        tabTitle.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                typeId = state[tab.getPosition()];
                loadData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        //添加回传数据
        foodEnergyAdapter.setItemListener(new AddFoodEnergyAdapter.ItemListener() {
            @Override
            public void ItemClick(FoodEnergy foodEnergy) {
                if (isManager) {
                    new AlertDialog.Builder(AddFoodEnergyActivity.this).setItems(new CharSequence[]{"编辑", "删除"}, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (which == 0) {
                                showEditDialog(foodEnergy);
                            } else if (which == 1) {
                                SQLiteDatabase writableDatabase = helper.getWritableDatabase();
                                writableDatabase.delete("food_energy", "id = ?", new String[]{foodEnergy.getId() + ""});
                                loadData();
                            }
                        }
                    }).show();
                } else {
                    Intent intent = new Intent();
                    intent.putExtra("foodEnergy", foodEnergy);
                    SQLiteDatabase writableDatabase = helper.getWritableDatabase();
                    foodEnergy.setCount(foodEnergy.getCount() + 1);
                    writableDatabase.update("food_energy", foodEnergy.toContentValues(), "id = ?", new String[]{foodEnergy.getId() + ""});
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        });
    }

    private void showEditDialog(FoodEnergy foodEnergy) {
        DialogEditEnergyBinding binding = DialogEditEnergyBinding.inflate(getLayoutInflater());
        binding.etCarbon.setText(foodEnergy.getCarbon() + "");
        binding.etFat.setText(foodEnergy.getFat() + "");
        binding.etHeat.setText(foodEnergy.getHeat());
        binding.etName.setText(foodEnergy.getFood());
        binding.etProtein.setText(foodEnergy.getProtein() + "");
        binding.etQuantity.setText(foodEnergy.getQuantity());
        AlertDialog show = new AlertDialog.Builder(this).setView(binding.getRoot()).show();
        binding.btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                show.dismiss();
            }
        });
        binding.btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String carbon = binding.etCarbon.getText().toString();
                String fat = binding.etFat.getText().toString();
                String heat = binding.etHeat.getText().toString();
                String name = binding.etName.getText().toString();
                String protein = binding.etProtein.getText().toString();
                String quantity = binding.etQuantity.getText().toString();
                if (carbon.isEmpty() || fat.isEmpty() || heat.isEmpty() || name.isEmpty() || protein.isEmpty() || quantity.isEmpty()) {
                    return;
                }
                foodEnergy.setFood(name);
                foodEnergy.setCarbon(Double.parseDouble(carbon));
                foodEnergy.setFat(Double.parseDouble(fat));
                foodEnergy.setHeat(heat);
                foodEnergy.setProtein(Double.parseDouble(protein));
                foodEnergy.setQuantity(quantity);
                SQLiteDatabase writableDatabase = helper.getWritableDatabase();
                writableDatabase.update("food_energy", foodEnergy.toContentValues(), "id = ?", new String[]{foodEnergy.getId() + ""});
                show.dismiss();
                loadData();
            }
        });
    }

    private void loadData() {
        String key = etSearch.getText().toString().trim();
        foodEnergyList = new ArrayList<>();
        FoodEnergy foodEnergy = null;
        String sql = "select * from food_energy where typeId = "+typeId+" and food like "+"'%"+key+"%'"+" order by count asc";
        SQLiteDatabase db = helper.getWritableDatabase();
        Cursor cursor = db.rawQuery(sql,null);
        if (cursor != null && cursor.getColumnCount() > 0) {
            while (cursor.moveToNext()) {
                Integer dbId = cursor.getInt(0);
                Integer typeId = cursor.getInt(1);
                String food = cursor.getString(2);
                String quantity = cursor.getString(3);
                String heat = cursor.getString(4);
                Double fat = cursor.getDouble(5);
                Double protein = cursor.getDouble(6);
                Double carbon = cursor.getDouble(7);
                int count = cursor.getInt(8);
                foodEnergy = new FoodEnergy(dbId, typeId, food, quantity, heat, fat, protein, carbon);
                foodEnergy.setCount(count);
                foodEnergyList.add(foodEnergy);
            }
        }
        Collections.reverse(foodEnergyList);
        if (foodEnergyList != null && foodEnergyList.size() > 0) {
            rvList.setVisibility(View.VISIBLE);
            llEmpty.setVisibility(View.GONE);
            foodEnergyAdapter.addItem(foodEnergyList);
        } else {
            rvList.setVisibility(View.GONE);
            llEmpty.setVisibility(View.VISIBLE);
        }
    }

    public void back(View view) {
        finish();
    }
}
